import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as _ from "lodash";
import { List, fromJS } from "immutable";
import Unit from "../models/Unit";
import Button from 'react-bootstrap/es/Button';
import FormControl from 'react-bootstrap/es/FormControl';
import ControlLabel from "react-bootstrap/es/ControlLabel";
import InputGroup from "react-bootstrap/es/InputGroup";
import FormGroup from 'react-bootstrap/es/FormGroup';
import { Form, ValidatedInput } from '../components/ReactBootstrapValidation';
import Row from "react-bootstrap/es/Row";
import Col from "react-bootstrap/es/Col";
import Checkbox from "react-bootstrap/es/Checkbox";
import ButtonToolbar from "react-bootstrap/es/ButtonToolbar";
import SplitButton from "react-bootstrap/es/SplitButton";
import Radio from "react-bootstrap/es/Radio";
import MenuItem from "react-bootstrap/es/MenuItem";
import { Table, Column, Cell } from "../components/Table";
import { toast, ToastContainer } from "react-toastify";
import { Modal, ModalHeader, ModalBody, ModalTitle, ModalFooter, ModalClose } from "../components/Modal";
import * as HttpClient from "../httpclient";

import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger'
import { combineReducers } from 'redux';
import {
  Store,
  compose,
  createStore,
  applyMiddleware
} from 'redux';

import {
  Provider, connect
} from 'react-redux';

//var styles = require('./sale-add.less');


function isNewUnit(unit) {
  return typeof unit.id === "string"
}

class TextCell extends React.PureComponent<any, any>{
  render() {
    const { rowIndex, data, columnKey, ...props } = this.props;
    let content;
    if (columnKey == "No") content = rowIndex + 1;
    else if (columnKey == 'unit_isdecimal') content = data.get(rowIndex)[columnKey] ? "不允许" : "允许"
    else content = data.get(rowIndex)[columnKey]
    return (
      <Cell {...props}>
        {
          content
        }
      </Cell>)
  }
};

class EditableCell extends React.PureComponent<any, any>{
  render() {
    const { rowIndex, data, columnKey, editRow, mouseOverRowIndex, ...props } = this.props;
    let content;
    if (columnKey == "Name") {
      content = (<div className="choseGoodArea" style={{ position: "relative", height: '26px' }}>
        <div style={{ position: "absolute", right: "54px", left: 0, top: '2px' }}>
          <input type="text"
            className="receiptsInputText"
            autoComplete="off"
            value={data.getIn([rowIndex, columnKey])}
            onChange={(e) => editRow(rowIndex, columnKey, e.target.value)} />
        </div>
        {mouseOverRowIndex == rowIndex && <a style={{ position: "absolute", right: 0 }} href="javascript:;" className="choseGoods">选择</a>}
      </div>)
    }
    else {
      content = (
        <input type="text"
          className="receiptsInputText"
          autoComplete="off"
          value={data.getIn([rowIndex, columnKey])}
          onChange={(e) => editRow(rowIndex, columnKey, e.target.value)} />
      )
    }
    return (
      <Cell {...props}>
        {content}
      </Cell>)
  }
};

var SortTypes = {
  ASC: 'ASC',
  DESC: 'DESC',
};

function reverseSortDirection(sortDir) {
  return sortDir === SortTypes.DESC ? SortTypes.ASC : SortTypes.DESC;
}


class SortHeaderCell extends React.PureComponent<any, any> {
  constructor(props) {
    super(props);

    this._onSortChange = this._onSortChange.bind(this);
  }

  render() {
    var { sortDir, children, onSortChange, ...props } = this.props;
    return (
      <Cell {...props}>
        <a onClick={this._onSortChange}>
          {children} {sortDir ? (sortDir === SortTypes.DESC ? '↓' : '↑') : ''}
        </a>
      </Cell>
    );
  }

  _onSortChange(e) {
    e.preventDefault();

    if (this.props.onSortChange) {
      this.props.onSortChange(
        this.props.columnKey,
        this.props.sortDir ?
          reverseSortDirection(this.props.sortDir) :
          SortTypes.DESC
      );
    }
  }
}

class CheckboxCell extends React.PureComponent<any, any>{
  render() {
    const { rowIndex, data, columnKey, checked, onChange, ...props } = this.props;
    const check = typeof checked == "function" ? checked(rowIndex, columnKey, data) : checked
    return (
      <Cell {...props}>
        <input type="checkbox" checked={check} onChange={e => onChange(e.target.checked, rowIndex, data)}></input>
      </Cell>)
  }
};


class ActionCell extends React.PureComponent<any, any>{
  render() {
    const { rowIndex, data, columnKey, onEdit, onDelete, ...props } = this.props;
    return (
      <Cell {...props}>
        <div className="tableButtonArea">
          <a className="operate edit" title="编辑" onClick={() => onEdit(rowIndex, data)}></a>
          <a className="operate del" title="删除" onClick={() => onDelete(rowIndex, data)}></a>
        </div>
      </Cell>)
  }
};



class App extends React.PureComponent<any, {
  units: List<Unit>,
  colSortDirs: any,
  columnWidths: object;
  mouseOverRowIndex: number;
  checkedAll: boolean,
  showAddModal: boolean,
  newUnit: Unit,
  newUnitChanged: boolean,
  isValid: boolean
}> {
  private _defaultSortIndexes;
  private _unitForm;
  private container;
  constructor(props, context) {
    super(props, context);
    this._defaultSortIndexes = [];
    this.state = {
      units: List<Unit>(),
      colSortDirs: {},
      columnWidths: {
        Name: 240,
        "Phone Number": 150,
        Email: 140,
        Address: 260,
      },
      mouseOverRowIndex: -1,
      checkedAll: false,
      showAddModal: false,
      newUnit: new Unit(),
      newUnitChanged: false,
      isValid: false
    }
    this._onColumnResizeEndCallback = this._onColumnResizeEndCallback.bind(this);
    this._onRowMouseEnter = this._onRowMouseEnter.bind(this);
    this._onRowMouseLeave = this._onRowMouseLeave.bind(this);
    this._editRow = this._editRow.bind(this);
    this._checkedAll = this._checkedAll.bind(this);
    this._rowIsChecked = this._rowIsChecked.bind(this);
    this._checkedRow = this._checkedRow.bind(this)
    this._rowClassNameGetter = this._rowClassNameGetter.bind(this);
    this._onAddUnit = this._onAddUnit.bind(this);
    this._onSortChange = this._onSortChange.bind(this);
    this._hideAddModal = this._hideAddModal.bind(this);
    this._showAddModal = this._showAddModal.bind(this);
    this._onDelCheckedUnit = this._onDelCheckedUnit.bind(this);

    HttpClient.getUnits().then((units) => {
      this.setState({ units: List<Unit>(units) })
    })
  }

  static childContextTypes = {
    addOneAfter: React.PropTypes.func,
    deleteOne: React.PropTypes.func,
    editProduct: React.PropTypes.func,
  }
  componentDidMount() {
  }

  componentWillUnmount() {
  }

  sortBy(name) {
    return (a, b) => {
      if (a.get(name) < b.get(name)) {
        return -1;
      }
      else if (a.get(name) > b.get(name)) {
        return 1;
      }
      return 0;
    }
  }

  // toast(level: 'error' | 'info' | 'success' | 'warning', title, message) {
  //   this.container[level](
  //     title,
  //     message, {
  //       timeOut: 5000,
  //       extendedTimeOut: 3000
  //     });
  // }

  _onColumnResizeEndCallback(newColumnWidth, columnKey) {
    this.setState(({ columnWidths }) => ({
      columnWidths: {
        ...columnWidths,
        [columnKey]: newColumnWidth,
      }
    }));
  }

  _onRowMouseEnter(event, rowIndex) {
    this.setState({
      mouseOverRowIndex: rowIndex
    })
  }

  _onRowMouseLeave(event, rowIndex) {
    this.setState({
      mouseOverRowIndex: -1
    })
  }

  getChildContext() {
    return {
    }
  }

  _editRow(rowIndex, columnKey, propValue) {
    const units = this.state.units;
    this.setState({ units: units.update(rowIndex, oldData => _.assign(new Unit(), oldData, _.object([columnKey], [propValue]))) });
  }

  _checkedAll(checked) {
    const units = this.state.units;
    this.setState({
      checkedAll: checked,
      units: units.withMutations(_units => {
        for (let i = 0; i < _units.size; i++) {
          _units.update(i, unit => _.assign(new Unit(), unit, { checked: checked }))
        }
      })
    });
  }

  _rowIsChecked(rowIndex, columnKey, data) {
    const units = this.state.units;
    return units.get(rowIndex).checked || false;
  }

  _checkedRow(checked, rowIndex, data) {
    this._editRow(rowIndex, "checked", checked);
    setTimeout(() => {
      if (this.state.units.filter(unit => unit.checked).size == 0) {
        this.setState({ checkedAll: false })
      }

      if (this.state.units.filter(unit => !unit.checked).size == 0) {
        this.setState({ checkedAll: true })
      }
    }, 0)
  }

  _rowClassNameGetter(rowIndex) {
    const units = this.state.units;
    return units.get(rowIndex).checked ? "row_highlighted" : "";
  }

  _showAddModal(unit) {
    this.setState({
      newUnit: unit,
      showAddModal: true,
      newUnitChanged: false
    })
  }

  _onSortChange(columnKey, sortDir) {
    const units = this.state.units;
    this.setState({
      units: units.sort((dataA, dataB) => {
        var valueA = dataA[columnKey];
        var valueB = dataB[columnKey];
        var sortVal = 0;
        if (valueA > valueB) {
          sortVal = 1;
        }
        if (valueA < valueB) {
          sortVal = -1;
        }
        if (sortVal !== 0 && sortDir === SortTypes.ASC) {
          sortVal = sortVal * -1;
        }
        return sortVal;
      }).toList(),
      colSortDirs: {
        [columnKey]: sortDir,
      },
    });
  }

  _hideAddModal() {
    this.setState({
      showAddModal: false,
      isValid: false
    })
  }

  _onAddUnit(unit: Unit) {
    HttpClient.createUnit(unit)
      .then((unit) => {
        this.setState({ units: this.state.units.push(unit) })
      })
  }

  _onDeleteUnit(unit: Unit) {
    if (window.confirm("您确认要删除吗？")) {
      HttpClient.deleteUnit(unit)
        .then(() => {
          this.setState({ units: this.state.units.filter(_unit => _unit.id != unit.id).toList() })
        })
    }
  }

  _onDelCheckedUnit() {
    const delUnits = this.state.units.filter(_unit => _unit.checked).toArray();
    if (delUnits.length == 0) {
      toast.warn("请选择要操作的数据！");
      return;
    }
    if (window.confirm("您确认要删除吗？")) {
      const delUnits = this.state.units.filter(_unit => _unit.checked).toArray();
      HttpClient.deleteUnit(delUnits)
        .then(() => {
          this.setState({ units: this.state.units.filter(_unit => _.findIndex(delUnits, delUnit => delUnit.id == _unit.id) == -1).toList() })
        })
    }
  }

  _editNewUnit(propValue) {
    console.log("_editunit", propValue)
    this.setState({
      newUnit: _.assign(new Unit(), this.state.newUnit, propValue),
      newUnitChanged: true
    })
  }

  render() {
    var state = this.state;
    var { columnWidths, mouseOverRowIndex, checkedAll, colSortDirs } = this.state;
    return (
      <div className="main">
        <ToastContainer ref={ref => { this.container = ref; }}
          position="top-center"
          type="default"
          autoClose={5000}
          preventDuplicates={true} />
        <ButtonToolbar className="whiteBox">
          <Button bsStyle="primary" bsSize="small" className="withIcon mr5" onClick={() => { this._showAddModal(new Unit()) }}>
            <span className="icon addIcon"></span>
            <span>新增单位</span>
          </Button>
          <SplitButton bsStyle="default" bsSize="small" id="test" title="批量操作">
            <MenuItem eventKey="1" onClick={this._onDelCheckedUnit}>删除</MenuItem>
          </SplitButton>
          <Button bsStyle="default" bsSize="small" className="mr5 pull-right">
            <span>搜索</span>
          </Button>
          <FormControl bsSize="small" className="mr5 pull-right" style={{ width: "243px" }} placeholder="搜索单位名称"></FormControl>
        </ButtonToolbar>

        <div className="whiteBox" ref="parent">
          <Table
            rowHeight={37}
            headerHeight={37}
            rowsCount={state.units.size}
            onColumnResizeEndCallback={this._onColumnResizeEndCallback}
            onRowMouseEnter={this._onRowMouseEnter}
            onRowMouseLeave={this._onRowMouseLeave}
            rowClassNameGetter={this._rowClassNameGetter}
            isColumnResizing={false}
            width={"100%"}
            maxHeight={300}
            className={"unitGrid"}
            {...this.props}>
            <Column
              columnKey="checkbox"
              align="center"
              header={<CheckboxCell checked={state.checkedAll} onChange={this._checkedAll} />}
              cell={<CheckboxCell data={state.units} checked={this._rowIsChecked} onChange={this._checkedRow} />}
              fixed={true}
              width={50}
            />
            <Column
              columnKey="No"
              align="center"
              header={<Cell>序号</Cell>}
              cell={<TextCell data={state.units} />}
              fixed={true}
              width={50}
            />
            <Column
              align="center"
              columnKey="unit_action"
              header={<Cell>操作</Cell>}
              cell={<ActionCell data={state.units}
                onEdit={(rowIndex, data) => this._showAddModal(state.units.get(rowIndex))}
                onDelete={(rowIndex, data) => {
                  this._onDeleteUnit(state.units.get(rowIndex))
                }} />}
              width={200}
            />
            <Column
              columnKey="unit_name"
              header={<SortHeaderCell
                onSortChange={this._onSortChange}
                sortDir={state.colSortDirs.unit_name}>
                单位名称
            </SortHeaderCell>}
              cell={<TextCell data={state.units} />}
              width={100}
              flexGrow={1}
            />
            <Column
              columnKey="unit_isdecimal"
              header={<Cell>允许小数</Cell>}
              align="center"
              cell={<TextCell data={state.units} />}
              width={80}
              flexGrow={1}
            />
            <Column
              columnKey="unit_remark"
              align="center"
              header={<Cell>备注</Cell>}
              cell={<TextCell data={state.units} />}
              width={60}
              flexGrow={1}
            //  isResizable={true}
            />
          </Table>
        </div>

        <Modal show={state.showAddModal} onHide={this._hideAddModal}>
          <ModalHeader>
            <ModalClose onClick={this._hideAddModal} />
            <ModalTitle className="pull-left">{isNewUnit(state.newUnit) ? "新增单位" : "编辑单位"}</ModalTitle>
          </ModalHeader>
          <ModalBody style={{ width: "500px" }}>
            <Form
              ref={ref => this._unitForm = ref}
              validateOne={(iptName, value, context, result) => {
                if (result !== true || iptName != "name") {
                  return result;
                }
                if (state.units.filter(unit => unit.unit_name == value && unit.id != state.newUnit.id).size > 0) {
                  return "已经占用"
                }
                else {
                  return true;
                }
              }}
              horizontal>
              <FormGroup
                bsSize="small"
                controlId="formHorizontalEmail">
                <Col componentClass={ControlLabel} sm={3}>
                  <span className="fontRed">*</span>单位名称
                </Col>
                <Col sm={9}>
                  <ValidatedInput name="name" type="text"
                    value={state.newUnit.unit_name || ""}
                    onChange={(e) => {
                      setTimeout(() => {
                        this.setState({
                          isValid: this._unitForm.isValid()
                        })
                      }, 100)
                      this._editNewUnit({ unit_name: e.target.value })
                    }}
                    validationEvent="onChange"
                    validate=''
                    validatingHelp={"正在验证"}
                    successHelp={"可以使用"}
                    errorHelp={{
                      required: '单位名称不能为空'
                    }} />
                </Col>
              </FormGroup>
              <FormGroup bsSize="small" controlId="formHorizontalPassword">
                <Col componentClass={ControlLabel} sm={3}>
                  允许小数
                </Col>
                <Col sm={9}>
                  <Radio
                    name="selIsDecimal"
                    checked={!state.newUnit.unit_isdecimal || true}
                    className="pull-left"
                    onChange={(e) =>
                      this._editNewUnit({ unit_isdecimal: !e.target.checked })
                    }
                    inline>允许小数</Radio>
                  <Radio name="selIsDecimal" checked={state.newUnit.unit_isdecimal || true}
                    className="pull-left"
                    onChange={(e) =>
                      this._editNewUnit({ unit_isdecimal: e.target.checked })
                    }
                    inline>不允许</Radio>
                </Col>
              </FormGroup>
              <FormGroup bsSize="small" controlId="formHorizontalMask" >
                <Col componentClass={ControlLabel} sm={3}>
                  备注
                </Col>
                <Col sm={9}>
                  <FormControl value={state.newUnit.unit_remark}
                    componentClass="textarea"
                    onChange={e =>
                      this._editNewUnit({ unit_remark: e.target.value })
                    } />
                </Col>
              </FormGroup>
            </Form>
          </ModalBody>
          <ModalFooter>
            {isNewUnit(state.newUnit) &&
              <Button bsStyle="primary"
                bsSize="small"
                disabled={!state.isValid}
                onClick={() => {
                  this._onAddUnit(this.state.newUnit);
                  this.setState({ newUnit: new Unit, isValid: false })
                  this._unitForm.reset();
                }}>
                保存并新增
            </Button>}
            <Button
              bsStyle={isNewUnit(state.newUnit) ? "default" : "primary"}
              bsSize="small"
              disabled={!state.newUnitChanged || !state.isValid}
              onClick={() => {
                this._onAddUnit(this.state.newUnit);
                this._hideAddModal()
              }}>
              保存
            </Button>
            <Button bsStyle="default" bsSize="small" onClick={this._hideAddModal}>
              取消
            </Button>
          </ModalFooter>
        </Modal>
      </div >
    );
  }
}


$(function () {
  // const reducers = combineReducers({
  // });

  // const initState = {
  // }
  // const middleware = applyMiddleware(createLogger(), thunkMiddleware);
  // const store = compose(middleware)(createStore)(reducers, initState);

  ReactDOM.render(
    //<Provider store={store}>
    <App></App>
    // </Provider>
    , document.getElementById('content')
  );
})
